/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.job.admin.manager;

import com.lvyh.lightframe.job.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;

@Service
public class ZkManager {

    private final static Logger logger = LoggerFactory.getLogger(ZkManager.class);

    /**
     * ZK connection address
     */
    @Value("${zk.registry.address}")
    private String zkUrl;

    private CuratorFramework client;

    /**
     * Start identification
     */
    private volatile boolean started = false;

    @PostConstruct
    public void init() {
        client = CuratorFrameworkFactory.builder().connectString(zkUrl).sessionTimeoutMs(30000).connectionTimeoutMs(30000)
                .canBeReadOnly(false).retryPolicy(new ExponentialBackoffRetry(5000, Integer.MAX_VALUE)).namespace(Constants.DEFAULT_ZK_NAMESPACE)
                .defaultData(null).build();

        client.start();
        started = true;
    }

    @PreDestroy
    public void destroy() {
        if (client != null) {
            client.close();
        }
    }

    public void addConnectionStateListener(ConnectionStateListener listener) {
        if (!started) {
            throw new RuntimeException("zkManager not started.");
        }
        this.client.getConnectionStateListenable().addListener(listener);
    }

    public String buildPath(String path, String... nodeNames) {
        StringBuilder pathBuilder = new StringBuilder(path);
        if (!StringUtils.endsWith(path, "/")) {
            pathBuilder.append("/");
        }
        if (nodeNames != null) {
            for (String nodeName : nodeNames) {
                if (StringUtils.startsWith(nodeName, "/")) {
                    nodeName = StringUtils.substring(nodeName, 1);
                }
                pathBuilder.append(nodeName);
                pathBuilder.append("/");
            }
        }
        int idx = pathBuilder.length() - 1;
        if (pathBuilder.charAt(idx) == '/') {
            pathBuilder.deleteCharAt(idx);
        }

        return pathBuilder.toString();
    }

    public boolean createEphemeralNode(String path, byte[] data) {
        try {
            if (data == null) {
                client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path);
            } else {
                String s = client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, data);
                System.out.println(s);
            }
            return true;
        } catch (KeeperException.NodeExistsException e) {
            logger.error("path:{} already existed", path);
            return false;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String getZkUrl() {
        return zkUrl;
    }

    public void setZkUrl(String zkUrl) {
        this.zkUrl = zkUrl;
    }

    public List<String> getChildren(String path) throws Exception {
        return client.getChildren().forPath(path);
    }

    public void watchChildren(String path, Watcher watcher) throws Exception {
        client.getChildren().usingWatcher(watcher).forPath(path);
    }

    public boolean deleteNode(String path) throws Exception {
        try {
            client.delete().forPath(path);
            return true;
        } catch (KeeperException.NoNodeException e) {
            logger.error("path:{} delete failed. because it not existed.");
            return true;
        } catch (Exception e) {
            logger.error("path:{} delete failed.", path);
            throw new RuntimeException(e);
        }
    }

    public boolean createPersistNode(String path, byte[] data) throws Exception {
        try {
            client.create().forPath(path, data);
            return true;
        } catch (KeeperException.NodeExistsException e) {
            return false;
        }
    }

}
